package cn.edu.jnu.supershopper;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookFragment extends Fragment{
    public static final int MENU_ID_ADD = 1;
    public static final int MENU_ID_UPDATE = 2;
    public static final int MENU_ID_DELETE = 3;
    private ArrayList<Book> BookList = new ArrayList<>();
    private static BookFragment.BookAdapter bookAdapter;
    FragmentTransaction transaction;

    private ActivityResultLauncher<Intent> addDataLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
                    ,result -> {
                        if(null!=result){
                            Intent intent=result.getData();
                            if(result.getResultCode() == EditBookActivity.RESULT_CODE_SUCCESS)
                            {
                                Bundle bundle=intent.getExtras();
                                String name = bundle.getString("name");
                                String isbn = bundle.getString("isbn");
                                String author = bundle.getString("author");
                                String published = bundle.getString("published");
                                String publishing = bundle.getString("publishing");
                                String score = bundle.getString("score");
                                String description = bundle.getString("description");
                                String author_info = bundle.getString("author_info");
                                String imagePath = bundle.getString("imagePath");
                                int position = bundle.getInt("position");
                                Book book = new Book(name,R.drawable.book_no_name);
                                book.setName(name);
                                book.setIsbn(isbn);
                                book.setAuthor(author);
                                book.setPublished(published);
                                book.setDoubanScore(score);
                                book.setDescription(description);
                                book.setPublishing(publishing);
                                book.setAuthorlntro(author_info);
                                book.setimagePath(imagePath);
                                BookList.add(position,book);
                                new BookDataSaver().Save(this.getContext(),BookList);
                                bookAdapter.notifyItemInserted(position);
                            }
                        }
                    });


    private ActivityResultLauncher<Intent> updateDataLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
                    ,result -> {
                        if(null!=result){
                            Intent intent=result.getData();
                            if(result.getResultCode()== EditBookActivity.RESULT_CODE_SUCCESS)
                            {
                                Bundle bundle=intent.getExtras();
                                String name = bundle.getString("name");
                                String isbn = bundle.getString("isbn");
                                String author = bundle.getString("author");
                                String published = bundle.getString("published");
                                String publishing = bundle.getString("publishing");
                                String score = bundle.getString("score");
                                String description = bundle.getString("description");
                                String author_info = bundle.getString("author_info");
                                String imagePath = bundle.getString("imagePath");
                                String label = bundle.getString("label");
                                int position = bundle.getInt("position");
                                BookList.get(position).setName(name);
                                BookList.get(position).setIsbn(isbn);
                                BookList.get(position).setAuthor(author);
                                BookList.get(position).setPublished(published);
                                BookList.get(position).setDoubanScore(score);
                                BookList.get(position).setDescription(description);
                                BookList.get(position).setPublishing(publishing);
                                BookList.get(position).setAuthorlntro(author_info);
                                BookList.get(position).setimagePath(imagePath);
                                BookList.get(position).setLabel(label);

                                new BookDataSaver().Save(this.getContext(),BookList);
                                bookAdapter.notifyItemChanged(position);
                            }
                        }
                    });


    //没用
    public BookFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment BookFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BookFragment newInstance() {
        BookFragment fragment = new BookFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_book_item, container, false);
        transaction = getFragmentManager().beginTransaction();
        BookDataSaver bookDataSaver =new BookDataSaver();
        BookList= bookDataSaver.Load(this.getContext());
        if(BookList.size()==0) {
            getListBooks();
            bookDataSaver.Save(this.getContext(),BookList);
        }

        RecyclerView recyclerView = rootView.findViewById(R.id.recycle_view_books);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(layoutManager);
        bookAdapter = new BookAdapter(BookList);

        bookAdapter.setOnItemClickLitener(new BookAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), ShowDetailsActivity.class);
                intent.putExtra("position", position);
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(bookAdapter);

        //两个悬浮按钮
        FloatingActionButton fab_add = rootView.findViewById(R.id.fab);
        fab_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(getActivity(), EditBookActivity.class);
                intent.putExtra("position",0);
                addDataLauncher.launch(intent);
            }
        });
        FloatingActionButton fab_search = rootView.findViewById(R.id.fab_search);
        fab_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), SearchActivity.class));
            }
        });

        return rootView;
    }

    //长按触发菜单
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId())
        {
            case MENU_ID_ADD:
                Intent intent=new Intent(this.getContext(), EditBookActivity.class);
                intent.putExtra("position",item.getOrder());
                addDataLauncher.launch(intent);
                break;
            case MENU_ID_UPDATE:
                Intent intentUpdate=new Intent(this.getContext(), EditBookActivity.class);
                intentUpdate.putExtra("position",item.getOrder());
                intentUpdate.putExtra("name",BookList.get(item.getOrder()).getName());
                intentUpdate.putExtra("cover",BookList.get(item.getOrder()).getImageId());
                intentUpdate.putExtra("URL",BookList.get(item.getOrder()).getPhotoUrl());
                intentUpdate.putExtra("isbn",BookList.get(item.getOrder()).getIsbn());
                intentUpdate.putExtra("author",BookList.get(item.getOrder()).getAuthor());
                intentUpdate.putExtra("author_info",BookList.get(item.getOrder()).getAuthorlntro());
                intentUpdate.putExtra("published",BookList.get(item.getOrder()).getPublished());
                intentUpdate.putExtra("score",BookList.get(item.getOrder()).getDoubanScore());
                intentUpdate.putExtra("publishing",BookList.get(item.getOrder()).getPublishing());
                intentUpdate.putExtra("description",BookList.get(item.getOrder()).getDescription());
                intentUpdate.putExtra("imagePath",BookList.get(item.getOrder()).getimagePath());
                updateDataLauncher.launch(intentUpdate);
                break;
            case MENU_ID_DELETE:
                AlertDialog alertDialog;
                alertDialog = new AlertDialog.Builder(this.getContext())
                        .setTitle(R.string.confirmation)
                        .setMessage(R.string.sure_to_delete)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                BookList.remove(item.getOrder());
                                new BookDataSaver().Save(BookFragment.this.getContext(),BookList);
                                bookAdapter.notifyItemRemoved(item.getOrder());
                            }
                        }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {}
                        }).create();
                alertDialog.show();
                break;
        }
        return super.onContextItemSelected(item);
    }

    public void getListBooks() {
        BookList.add(new Book("软件项目管理案例教程（第4版）", R.drawable.book_2));
        BookList.add(new Book("创新工程实践", R.drawable.book_no_name));
        BookList.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1));
    }


    static class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> {
        private final List<Book> mBookList;

        private OnItemClickLitener mOnItemClickLitener;

        //设置回调接口
        public interface OnItemClickLitener{
            void onItemClick(View view, int position);
        }

        public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener){
            this.mOnItemClickLitener = mOnItemClickLitener;
        }

        public BookAdapter(List<Book> bookList) {
            mBookList = bookList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            Book book = mBookList.get(position);
            holder.bookName.setText(book.getName());
            holder.bookAuthor.setText(book.getAuthor());
            holder.bookPublished.setText(book.getPublished());
            holder.bookISBN.setText(book.getIsbn());
            holder.bookPublishing.setText(book.getPublishing());
            holder.bookScore.setText(book.getDoubanScore());
            switch (book.getLabel()){
                default:holder.label.setText(book.getLabel());
                case "正常":
                    holder.label.setBackgroundColor(Color.GREEN);
                    break;
                case "未读":
                    holder.label.setBackgroundColor(Color.YELLOW);
                    break;
                case "借出":
                    holder.label.setBackgroundColor(Color.BLUE);
                    break;
                case "丢失":
                    holder.label.setBackgroundColor(Color.rgb(136, 0, 85));
                    break;
                case "损毁":
                    holder.label.setBackgroundColor(Color.RED);
                    break;
                case "其他":
                    holder.label.setBackgroundColor(Color.rgb(210,210,210));
                    break;

            }
            holder.label.setText(book.getLabel());

            String URL = book.getPhotoUrl();
            String imagePath = book.getimagePath();
            if(imagePath!=null){
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                holder.bookImage.setImageBitmap(bitmap);}
            else {
                if(!URL.equals("暂无信息"))holder.bookImage.setImageURL(URL);
                else if(book.getImageId()>10)holder.bookImage.setImageResource(book.getImageId());
            }

            //通过为条目设置点击事件触发回调
            if (mOnItemClickLitener != null) {
                holder.layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mOnItemClickLitener.onItemClick(view, holder.getAdapterPosition());
                    }
                });
            }
        }


        class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            MyImageView bookImage;
            TextView bookName;
            TextView bookAuthor;
            TextView bookPublished;
            TextView bookISBN;
            TextView bookPublishing;
            TextView bookScore;
            TextView label;
            FrameLayout layout;

            public ViewHolder(View view) {
                super(view);
                bookImage = view.findViewById(R.id.image_view_book_cover);
                bookName = view.findViewById(R.id.text_view_book_title);
                bookAuthor = view.findViewById(R.id.item_author);
                bookPublished = view.findViewById(R.id.item_poblished);
                bookISBN = view.findViewById(R.id.item_ISBN);
                bookPublishing = view.findViewById(R.id.item_publishing);
                bookScore = view.findViewById(R.id.item_score);
                label = view.findViewById(R.id.item_label);
                layout = view.findViewById(R.id.item);
                view.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu
                    (ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                contextMenu.add(0,MENU_ID_ADD,getAbsoluteAdapterPosition(),"上方添加");
                contextMenu.add(0,MENU_ID_UPDATE,getAbsoluteAdapterPosition(),"修改信息");
                contextMenu.add(0,MENU_ID_DELETE,getAbsoluteAdapterPosition(),"删除书籍");
            }
        }


        @Override
        public int getItemCount() {
            return mBookList.size();
        }

    }

}